package cn.edu.scau.vsac.service.impl;

import cn.edu.scau.vsac.dao.HelpOfferDao;
import cn.edu.scau.vsac.domain.dto.HelpOfferDto;
import cn.edu.scau.vsac.entity.HelpOffer;
import cn.edu.scau.vsac.entity.HelpRequest;
import cn.edu.scau.vsac.service.HelpOfferService;
import cn.edu.scau.vsac.service.HelpRequestService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 我要帮扶表（help_offer）(HelpOffer)表服务实现类
 *
 * @author makejava
 * @since 2023-08-05 20:12:18
 */
@Service("helpOfferService")
public class HelpOfferServiceImpl extends ServiceImpl<HelpOfferDao, HelpOffer> implements HelpOfferService {
    @Autowired
    HelpRequestService helpRequestService;

    @Override
    public HelpOffer getOneById(Long id) {
        return this.getById(id);
    }

    @Override
    public String deleteById(Long id) {
        HelpOffer offer = this.getById(id);
        if (offer == null) return null;
        HelpRequest byId = helpRequestService.getById(offer.getRequestId());
        if (byId == null) return null;
        byId.setIsHelped(0);
        helpRequestService.save(byId);
        boolean b = this.removeById(id);
        if (b) return "deleted success";
        return null;
    }

    @Override
    public HelpOffer create(HelpOfferDto helpOfferDto) {
        HelpOffer offer = new HelpOffer();
        offer.setHelperId(helpOfferDto.getHelperId());
        offer.setOfferContent(helpOfferDto.getOfferContent());
        offer.setHelperUsername(helpOfferDto.getHelperUsername());
        offer.setRequestId(helpOfferDto.getRequestId());
        boolean save = this.save(offer);
        if(!save) return null;
        HelpRequest byId = helpRequestService.getById(offer.getRequestId());
        if (byId == null) return null;
        byId.setIsHelped(1);
        helpRequestService.save(byId);
		return offer;
    }

    @Override
    public List<HelpOffer> getPageByHelperId(Long helperId) {
        QueryWrapper<HelpOffer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("helper_id", helperId);
        return this.list(queryWrapper);
    }

    @Override
    public HelpOffer getByRequestId(Long requestId) {
        QueryWrapper<HelpOffer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("request_id", requestId);
        HelpOffer one = this.getOne(queryWrapper);
        return one;
    }
}

